package cn.dapeng.interview;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 实现一个容器，提供两个方法 add和size
 * 写两个线程 线程1添加10个元素，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束??
 * <p>
 * <p>
 * <p>
 * 这种写法实现不了
 */
public class Taobao_With_Volatile {

    volatile List<Integer> list = Collections.synchronizedList(new ArrayList<>());

    public synchronized void add(int num) {
        list.add(num);
    }

    public synchronized int size() {
        return list.size();
    }

    public static void main(String[] args) {

        Taobao_With_Volatile taobao = new Taobao_With_Volatile();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                taobao.add(i);
                System.out.println("add" + i);
                //SleepingUtil.sleep(1, TimeUnit.SECONDS);
            }
        });
        t1.start();

        new Thread(() -> {
            while (true) {
                if (taobao.size() == 5) {
                    System.out.println("t2 end");
                    break;
                }

            }
        }).start();
    }
}
